<script setup>
// import语句
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getgradelist,
  creategrade,
  creategradename,
  deletegrade,
  deletegradename,
  updategrade,
} from '@/api/gradeManagement.js'

// 响应式变量定义
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  tngId: '', // 教师-年级ID
})
const jumpPage = ref(1)

// 表格相关
const loading = ref(false)
const total = ref(0)
const gradeList = ref({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 1,
})
const gradeNameMap = ref({
  name: '学生名称',
  deptName: '班级',
  phone: '电话',
  gradeNameList: [],
})

// 获取成绩列表数据
const getGradeList = async () => {
  loading.value = true
  try {
    const { code, data, msg } = await getgradelist(queryParams)
    if (code !== 200) {
      throw new Error(msg)
    }

    // 更新数据结构以匹配API返回
    if (data.gradeList && data.gradeList.records) {
      gradeList.value = data.gradeList
      total.value = data.gradeList.total || 0
    }

    // 处理成绩名称映射
    if (data.gradeNameMap && data.gradeNameMap.gradeNameList) {
      gradeNameMap.value = data.gradeNameMap
    }

    console.log('获取的数据:', gradeList.value, gradeNameMap.value)
  } catch (error) {
    ElMessage.error(error.message || '获取成绩数据失败')
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getGradeList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getGradeList()
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getGradeList()
}

// 添加页面跳转功能
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (
    isNaN(pageNum) ||
    pageNum < 1 ||
    pageNum > Math.ceil(total.value / queryParams.pageSize)
  ) {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = queryParams.pageNum
    return
  }
  queryParams.pageNum = pageNum
  getGradeList()
}

// 编辑成绩
const handleEditGrade = async (row, gradeNameItem, index) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入新的成绩', '编辑成绩', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: row.gradeList[index] || '',
      inputPattern: /^(\d+(\.\d+)?)$/,
      inputErrorMessage: '请输入有效的成绩分数',
    })

    const gradeValue = parseFloat(value)

    // 验证成绩是否在有效范围内
    const maxGrade = gradeNameItem.maxGrade || 100 // 如果没有maxGrade，默认为100

    if (maxGrade && gradeValue > maxGrade) {
      ElMessage.warning(`成绩不能超过满分${maxGrade}`)
      return
    }

    const params = {
      id: row.gradeIdList ? row.gradeIdList[index] : undefined,
      tgnId: gradeNameItem.id || index + 1, // 使用索引+1作为备选的tgnId
      grade: gradeValue,
      userId: row.userId || row.id, // 使用id作为备选的userId
    }

    // 根据是否有成绩ID决定是创建还是更新
    const api = params.id ? updategrade : creategrade
    const { code, msg } = await api(params)

    if (code === 200) {
      ElMessage.success('保存成绩成功')
      getGradeList() // 刷新数据
    } else {
      throw new Error(msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '操作失败')
    }
  }
}

// 添加成绩项
const handleAddGradeName = async () => {
  try {
    // 获取课程ID，这通常是从路由或其他地方获取的
    // 这里简化处理，实际应用可能需要从页面参数或下拉列表中获取
    const tcdId = queryParams.tngId || 1

    const gradeNameForm = reactive({
      tcdId: tcdId,
      gradeName: '',
      passGrade: 60,
      maxGrade: 100,
    })

    await ElMessageBox.prompt('请输入成绩项名称', '添加成绩项', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入成绩项名称',
      inputValidator: (value) => !!value.trim() || '成绩项名称不能为空',
    })
      .then(({ value }) => {
        gradeNameForm.gradeName = value.trim()
        return creategradename(gradeNameForm)
      })
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success('添加成绩项成功')
          getGradeList()
        } else {
          throw new Error(res.msg || '添加失败')
        }
      })
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '添加成绩项失败')
    }
  }
}

// 删除成绩项
const handleDeleteGradeName = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除成绩项"${item.gradeName}"吗？这将删除所有相关的成绩数据。`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    console.log('删除的成绩项:', item)

    const { code, msg } = await deletegradename({ id: item.id })
    if (code === 200) {
      ElMessage.success('删除成绩项成功')
      getGradeList()
    } else {
      throw new Error(msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除成绩项失败')
    }
  }
}

// 生命周期
onMounted(() => {
  getGradeList()
})
</script>

<template>
  <div class="grade-manage p-4" tabindex="0">
    <!-- 操作按钮区域 -->
    <div class="mb-4 flex flex-wrap gap-2 items-center">
      <el-input
        v-model="queryParams.name"
        placeholder="请输入学生姓名"
        style="width: 200px"
        clearable
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="handleAddGradeName"
        >添加成绩项</el-button
      >
    </div>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="gradeList.records" border>
      <!-- 固定列：学生名称、班级、电话 -->
      <el-table-column
        prop="name"
        label="学生姓名"
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="deptName"
        label="班级"
        min-width="150"
      ></el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        min-width="120"
      ></el-table-column>

      <!-- 动态列：成绩项 -->
      <el-table-column
        v-for="(item, index) in gradeNameMap.gradeNameList"
        :key="index"
        :label="item.gradeName"
        min-width="120"
        align="center"
      >
        <template #header>
          <div class="flex flex-col items-center">
            <span>{{ item.gradeName }}</span>
            <!-- <div class="text-xs text-gray-500 mt-1">
              <span>及格: {{ item.passGrade }}</span>
            </div> -->
            <el-button
              type="danger"
              size="small"
              @click.stop="handleDeleteGradeName(item)"
              class="mt-1 !h-6 text-xs"
            >
              删除
            </el-button>
          </div>
        </template>

        <template #default="scope">
          <div
            :class="[
              'grade-cell',
              scope.row.gradeList && scope.row.gradeList[index] !== undefined
                ? Number(scope.row.gradeList[index]) >= item.passGrade
                  ? 'text-success'
                  : 'text-danger'
                : '',
            ]"
            @click="handleEditGrade(scope.row, item, index)"
          >
            {{
              scope.row.gradeList && scope.row.gradeList[index] !== undefined
                ? scope.row.gradeList[index]
                : '-'
            }}
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="queryParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          :total="total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.grade-manage {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .el-table {
    height: calc(100vh - 270px);
  }
}

.grade-cell {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;

  &:hover {
    background-color: #f5f7fa;
  }

  &.text-success {
    color: #67c23a;
  }

  &.text-danger {
    color: #f56c6c;
  }
}
</style>
